<template>
  <div class="music_table_container">
    <el-table :data="tracks" style="width: 100%" @cell-mouse-enter="handleMouseEnterTableCell"
      @cell-mouse-leave="handleMouseLeaveTableCell">
      <el-table-column prop="index" width="74" show-overflow-tooltip :label="type == 'player' ? '序号' : ''">
        <template #default="scope">
          <div :class="isCurSong(scope.row)">
            <!-- :class="[scope.row.fee == 1 || scope.row.license ? 'vip' : '']" -->
            <span class="songlist-index" v-show="type != 'player' || !showTableTime || rowId != scope.row.id">{{ scope.$index + 1 }}</span>
            <!-- 音频动画 -->
            <div v-if="type == 'player'">
              <div class="audio-icon" v-show="!showTableTime || rowId != scope.row.id">
                <div class="column" style="animation-delay: -1.2s"></div>
                <div class="column"></div>
                <div class="column" style="animation-delay: -1.5s"></div>
                <div class="column" style="animation-delay: -0.9s"></div>
                <div class="column" style="animation-delay: -0.6s"></div>
              </div>
              <!-- 按钮 -->
              <i v-show="showTableTime && rowId == scope.row.id" :class="playIcon(scope.row)" @click="currentSong(scope.row)"></i>
            </div>
            <el-icon :size="17" class="cursor_class" @click="handleClickPlay(scope.row)" v-else>
              <VideoPlay />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="歌曲标题" :width="type == 'player' ? 'auto' : '400'" show-overflow-tooltip>
        <template #default="scope">
          <el-tag v-if="scope.row.fee == 1 || scope.row.license" type="danger" effect="dark" style="margin-right:4px">
            VIP</el-tag>
          <a :href="'/discover/song/' + scope.row.id">{{
          scope.row.name
          }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="时长" :width="type == 'player' ? 'auto' : '180'" show-overflow-tooltip>
        <template #default="scope">
          <div style="height: 23px" v-if="showTableTime && rowId == scope.row.id">
            <el-tooltip effect="dark" content="添加到播放列表" placement="top-start" v-if="type != 'player'">
              <span class="cursor_class table_opeat" @click="addListData(scope.row)">
                <el-icon>
                  <Plus />
                </el-icon>
              </span>
            </el-tooltip>
            <el-tooltip effect="dark" content="收藏" placement="top-start">
              <span class="cursor_class table_opeat" style="margin-left: 8px" @click="collection(scope.row)">
                <el-icon>
                  <FolderAdd />
                </el-icon>
              </span>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top-start" v-if="type == 'player' || deletedBtn && localUserId === userId">
              <span class="cursor_class table_opeat" style="margin-left: 8px" @click="tracksDelete(scope.row.id, scope.$index)">
                <el-icon>
                  <DeleteFilled />
                </el-icon>
              </span>
            </el-tooltip>
          </div>
          <div v-else style="height: 23px">{{
          dayjs(scope.row.dt).format('mm:ss') }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="ar" label="歌手" show-overflow-tooltip v-if="artistColumn">
        <template #default="scope">
          <div style="display:flex" v-if="scope.row.ar">
            <div v-for="(item, index) in scope.row.ar" :key="index" class="text_ellipsis">
              <span v-if="index !== 0" style="margin:0 4px">/</span>
              <a :href="'/discover/artist-detail/' + item.id" class="text_decoration">
                {{ item.name }}
              </a>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="al" label="专辑" show-overflow-tooltip v-if="type != 'player'">
        <template #default="scope">
          <a v-if="scope.row.al" :href="'/discover/album-detail/' + scope.row.al.id" :class="['text_decoration']">{{
          scope.row.al.name
          }}</a>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <Collection ref="collectionRef" />
</template>

<script lang="ts" setup>
import { useStore } from "vuex";
import {
  Plus,
  VideoPlay,
  DocumentAdd,
  Comment,
  FolderAdd,
  DeleteFilled,
  Edit,
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Collection from "@/components/Collection/index"
import { reactive, ref, getCurrentInstance, toRefs, computed } from 'vue'
import { useRouter } from 'vue-router'
import router from '@/router';
import dayjs from "dayjs";
import { collectionTypeRef } from "@/types/collection";
import * as myMusicApi from '@/api/my-music'
const store = useStore();
const props = defineProps({
  // 歌曲列表
  tracks: {
    type: Array as unknown as any[],
    default: () => [{ al: {} }],
    require: true
  },
  // 歌单id
  playListId: {
    type: Number,
    default: 0
  },
  // 是否需要删除按钮 要删除按钮必须传递歌单id
  deletedBtn: {
    type: Boolean,
    default: false
  },
  // 是否需要歌手列
  artistColumn: {
    type: Boolean,
    default: true
  },
  // 用户id 要删除按钮必须用户id
  userId: {
    type: Number,
    default: 0
  },
  type: {
    type: String,
    default: ''
  }
})
const { tracks, playListId, deletedBtn, userId, type } = toRefs(props)
const playList = computed(() => store.getters.playList)
const isPlayed = computed(() => store.getters.isPlayed)
// 获取当前播放音乐信息
const curSongInfo = computed(() => {
  return playList.value[store.getters.playIndex]
})
// 序号及播放状态
const playIcon = computed(() => {
  return (item: any) => {
    return [
      'iconfont',
      'playicon',
      isPlayed.value && item.id === curSongInfo.value.id
        ? 'icon-pause'
        : 'icon-play',
    ]
  }
})
const { proxy }: any = getCurrentInstance()
const route = useRouter()
// 歌单列表是否显示时长
const showTableTime = ref(true)
const rowId = ref('')
const collectionRef = ref<collectionTypeRef | null>(null)
let userInfo = proxy.$getUserInfo()
const localUserId = ref<number | null>(JSON.stringify(userInfo) === '{}' ? 0 : userInfo.userId)
/**
 * 歌单列表表格鼠标移入单元格事件
 */
const handleMouseEnterTableCell = (row: any, column: any, cell: any, event: any) => {
  showTableTime.value = true
  rowId.value = row.id
}
/**
 * 歌单列表表格鼠标移出单元格事件
 */
const handleMouseLeaveTableCell = (row: any, column: any, cell: any, event: any) => {
  showTableTime.value = false
  rowId.value = ''
}
// 收藏
const collection = (row: any) => {
  checkMusicData(row, 3)
}
// 删除歌单的歌曲
const tracksDelete = async (id: number, index: number) => {
  if(type.value === 'player') {
    if (playList.value.length > 1) {
      let newArr = [...playList.value]
      newArr.splice(index, 1)
      store.dispatch('delList', { list: newArr });
    } else {
      store.dispatch('delList', { list: [] });
    }
  } else {
    ElMessageBox.confirm('确定删除歌曲？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        let cookie = localStorage.getItem('cookie')
        await myMusicApi.tracks({ op: 'del', pid: props.playListId, tracks: id, cookie })
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      } catch (error) {
        console.log(error);
      }
    }).catch(() => {

    })
  }
  
}
// 播放歌曲
const handleClickPlay = (row: any) => {
  if (row.fee == 1) {
    ElMessage({
      message: '当前音乐不可用',
      type: 'error',
    })
    return;
  }
  checkMusicData(row, 1)
}
const addListData = (row: any) => {
  checkMusicData(row, 2)
}
// 检测音乐是否可用
const checkMusicData = async (row: any, num: number) => {
  const res: any = await myMusicApi.checkMusic({
    id: row.id
  })
  if (res.success) {
    if (num === 1) {
      store.dispatch('selectPlay', { list: [row] });
    } else if (num === 2) {
      store.dispatch('addList', { list: [row] });
    } else if (num === 3) {
      if (collectionRef.value) {
        collectionRef.value.id = row.id
        collectionRef.value.isSongSheet = false
        collectionRef.value.dialogVisible = true
        collectionRef.value.init()
      }
    }
  } else {
    ElMessage({
      message: res.message || '当前音乐不可用',
      type: 'error',
    })
  }
}
// 播放当前播放歌曲
const currentSong = (item: any) => {
  // 若当前唔歌曲 或者 当前播放歌曲不是本歌单显示的歌曲  立即播放当前歌单
  if (!curSongInfo.value || item.id !== curSongInfo.value.id) {
    store.dispatch('selectPlay', { list: [item] })
    // if (this.isShowTips) {
    //     this.setPlayListTips({ flag: true, txt: '已开始播放' })
    //     clearTimeout(this.timer)
    //     this.timer = setTimeout(() => {
    //         this.setPlayListTips({ flag: false, txt: '已开始播放' })
    //     }, 2000)
    // }
  } else {
    store.commit('SET_PLAYSTATUS', !isPlayed.value)
  }
}
// 列表样式
const isCurSong = computed(() => {
  return (item: any, index: number) => {
    return [
      'music_table_index',
      type.value === 'player' && isPlayed.value && item.id === curSongInfo.value.id ? 'active' : '',
    ]
  }
})
</script>
<style lang="scss" scoped>
.music_table_container {
  a {
    color: #333;

    &:hover {
      color: #333;
    }
  }

  .music_table_index {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-icon {
      &:hover {
        color: #409eff;
      }
    }
  }

  .table_opeat {
    font-size: 16px;
  }
}
// 解决player的el-popper的light模式下影响el-popper的dark模式
:deep(.el-popper .el-popper__arrow::before) {
  border: 1px solid var(--el-text-color-primary) !important;
  background: var(--el-text-color-primary) !important;
}
.music_table_index {
  .icon-pause {
    color: var(--el-color-primary);
  }
  .audio-icon {
    display: none;
    width: 20px;
    height: 18px;
    overflow: hidden;

    .column {
      width: 2px;
      height: 100%;
      margin-left: 2px;
      background-color: var(--el-color-primary);
      -webkit-animation: play 0.9s linear infinite alternate;
      animation: play 0.9s linear infinite alternate;
    }
  }
  i:hover {
    color: var(--el-color-primary);
    cursor: pointer;
  }
  &.active {
    .songlist-index {
      display: none;
    }

    .audio-icon {
      display: flex;
    }

    &:hover {
      .playicon {
        display: block;
        color: var(--el-color-primary);
      }
      .audio-icon {
        display: none;
      }
    }
  }
}
@-webkit-keyframes play {
  0% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }

  to {
    -webkit-transform: translateY(75%);
    transform: translateY(75%);
  }
}

@keyframes play {
  0% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }

  to {
    -webkit-transform: translateY(75%);
    transform: translateY(75%);
  }
}
</style>
